// backpage/service/impl/AnnualLeaveServiceImpl.java
package backpage.service.Impl;

import backpage.entity.AnnualLeave;
import backpage.entity.Employee;
import backpage.mapper.AnnualLeaveMapper;
import backpage.mapper.EmployeeMapper;
import backpage.service.AnnualLeaveService;
import backpage.service.EmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class AnnualLeaveServiceImpl
        extends ServiceImpl<AnnualLeaveMapper, AnnualLeave>
        implements AnnualLeaveService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<AnnualLeave> queryRecords(Integer currentUserId, Integer departmentId, Integer role) {
        LambdaQueryWrapper<AnnualLeave> wrapper = new LambdaQueryWrapper<>();

        if (!isAdmin(departmentId, role)) {
            wrapper.eq(AnnualLeave::getEmployeeId, currentUserId);
        }

        // 按申请ID降序
        wrapper.orderByDesc(AnnualLeave::getRegistrationId); // 新增排序

        return this.list(wrapper);
    }

    private boolean isAdmin(Integer departmentId, Integer role) {
        return departmentId != null && role != null
                && departmentId == 3
                && role == 1;
    }

    private final EmployeeService employeeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processApplication(Long registrationId, Integer status, Integer operatorId) {
        // 1. 通过registration_id获取申请记录
        AnnualLeave record = getById(registrationId);
        if (record == null || record.getStatus() != 0) {
            throw new RuntimeException("申请记录不存在或已处理");
        }

        // 2. 校验操作权限
        if (!operatorId.equals(record.getOperator())) {
            throw new RuntimeException("无操作权限");
        }

        // 3. 更新员工年假余额（原逻辑不变）
        if (status == 1) {
            Employee employee = employeeService.queryEmpInfoById(record.getEmployeeId());
            // 新增校验逻辑（关键代码）
            if (employee.getRemainingAnnualLeave() < record.getDaysLeave()) {
                throw new RuntimeException("剩余年假不足，当前剩余：" + employee.getRemainingAnnualLeave() + "天");
            }
            // 原扣减逻辑保持不变
            employee.setRemainingAnnualLeave(
                    employee.getRemainingAnnualLeave() - record.getDaysLeave()
            );
            employeeService.updateEmpInfo(employee);
        }

        // 4. 更新审批记录
        record.setStatus(status);
        record.setDateOperateLeave(new Date());
        return updateById(record);
    }
}
